﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace FotoLab.DataLayer.JpegStorage
{

    public enum JpegResolutie
    {

        High,
        Medium,
        Thumbnail

    }

    static class JpegResolutieExtension
    {

        public static Stream Resize(this JpegResolutie resolutie, Stream origineel)
        {
            /*
                Een foto met lage resolutie en ook thumbnails altijd de huidige verhoudingen breedte, hoogte aanhouden.
                Zorg dat de foto's maximaal 800x600 zijn of verzin een waarde
            */

            Stream result;

            if (resolutie == JpegResolutie.High)
            {
                result = origineel;
            }
            else
            {
                Bitmap original = (Bitmap)Image.FromStream(origineel);

                Dimension maxDimension = resolutie.GetMaxAfmeting();
                Dimension originalDimension = new Dimension()
                {
                    Width = original.Width,
                    Height = original.Height
                };

                float scale;

                // check of landscape is
                if (originalDimension.GetRatio() >= maxDimension.GetRatio())
                {
                    // landscape
                    scale = ((float) maxDimension.Width / (float)originalDimension.Width);
                }
                else
                {
                    // portrait
                    scale = ((float)maxDimension.Height / (float)originalDimension.Height);
                }

                int resizedWidth = (int)(originalDimension.Width * scale);
                int resizedHeight = (int)(originalDimension.Height * scale);

                Bitmap resized = new Bitmap(original, new Size(resizedWidth, resizedHeight));

                result = new MemoryStream();
                resized.Save(result, ImageFormat.Jpeg);
            }

            result.Seek(0, SeekOrigin.Begin);
            return result;
        }

        private class Dimension
        {
            public int Width { get; set; }
            public int Height { get; set; }

            public float GetRatio()
            {
                return (float)Width / (float)Height;
            }
        }

        private static Dimension GetMaxAfmeting(this JpegResolutie resolutie)
        {
            switch (resolutie)
            {
                case JpegResolutie.Medium:
                    return new Dimension { Width = 800, Height = 600 };
                case JpegResolutie.Thumbnail:
                    return new Dimension { Width = 100, Height = 100 };
                default:
                    throw new NotImplementedException();
            }

        }

    }


}